<?php

namespace App\Http\Middleware;

use Closure;

class NormalizePageAndPerPage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->isMethod('get')) {
            $request->page = intval($request->page);
            $request->per_page = intval($request->per_page) ?: intval($request->limit);
            $request->page = $request->page >= 1 ? $request->page : 1;
            $request->per_page =
                $request->per_page >= 1 ? $request->per_page : 10;
        }
        return $next($request);
    }
}
